<template>
	<view class="">
		<view class="uni-page-head" v-if="titleFlag">
			<image class="common-title-img" style="left: 20rpx;"
				:src="require('../../static/imges/fanhui.png')" @click="back()"></image>
				<!-- <view class="common-title-img">
					<u-icon name="arrow-right" color="#FFFFFF" width="20rpx" height="20rpx" size="48" @click="back()"></u-icon>
				</view> -->
				
				
			<view class="uni-page-head-title">
				冲销验工计价
			</view>
		</view>
		<view v-if="titleFlag" style="margin-top: 98rpx;">
			<!-- 这个盒子是用来撑空间，又不想改变下边的body盒子 所以在这加了一个空盒子，可以根据新老MOA判断 -->
		</view>
		<view class="common-body" v-for="(item,index) in baseList" :key="index">
			<u-collapse style="border: 1px solid #EAEAEA;">
				<u-collapse-item>
					<template v-slot:title>
						<view style="font-weight: bold;margin-left: 5px;">冲销说明</view>
					</template>
					<view>
						如果预估单有首付款且数量为0，那么全量冲销进度款时请先冲销首付款，再冲销进度款！
					</view>
				</u-collapse-item>
			</u-collapse>
			<view class="common-list">

				<label class="common-list-title">供应商名称 :</label>

				<text class="common-list-text" :selectable="true">{{item.supplierName}}</text>

			</view>
			<view class="common-list">

				<label class="common-list-title">订单编号 :</label>

				<text class="common-list-text" :selectable="true">{{item.orderCode}}</text>

			</view>
			<view class="common-list">

				<label class="common-list-title">合同编码 :</label>

				<text class="common-list-text" :selectable="true">{{item.contractCode}}</text>

			</view>
			<view class="common-list">
				<view style="width:50%;">
					<label class="common-list-title">订单状态 :</label>

					<text class="common-list-text">{{item.orderState}}</text>
				</view>
				<view style="width:50%;margin-left: 20px;">
					<label class="common-list-title">录入计价次数 :</label>

					<text class="common-list-text">{{item.valuationDetails.length}}</text>
				</view>

			</view>
			<view class="common-list">

				<label class="common-list-title">商合预占数 :</label>

				<text class="common-list-text">{{item.shNum}}</text>

			</view>
			<view class="common-list">

				<label class="common-list-title">单价（元） :</label>

				<text class="common-list-text">{{item.price}}</text>

			</view>
			<view class="common-list">

				<label class="common-list-title">商合预占金额 :</label>

				<text class="common-list-text">{{item.shMoney}}</text>

			</view>
			<view class="common-list">

				<label class="common-list-title">累计验工数量 :</label>

				<text class="common-list-text">{{item.sumNum}}</text>

			</view>
			<view class="common-list">

				<label class="common-list-title">累计验工金额 :</label>

				<text class="common-list-text">{{item.sumMoney}}</text>

			</view>
		</view>


		<!-- 填写区 -->
		<view class="common-body-ex">
			<view class="common-list-ex">

				<label class="common-list-title-ex">付款类型 :</label>
				<view class="">

					<label class="radio">
						<radio value="r1" :checked="checked" @click="radioChange()" />进度款
					</label>
					<label class="radio" v-if="sfkflag">
						<radio value="r2" :checked="checked2" @click="radioChange2()" />首付款（含安全生产费）
					</label>

				</view>
			</view>
			<view class="common-list-ex" style="background-color: #FFFBE5;">

				<label class="common-list-title-ex"><text class="colorRed">*</text>项目进度（%） :</label>

				<input  @input="inputClick" class="common-list-inpur-ex" type="digit"  v-model="currentjindu"
					placeholder="请输入" />

			</view>
			<view class="common-list-ex"  style="background-color: #FFFBE5;">

				<label class="common-list-title-ex"><text class="colorRed">*</text>本期冲销数量 :</label>

				<input @input="blurclick" class="common-list-inpur-ex" type="digit"  v-model="currentNum"
					:disabled="disabledNum" placeholder="所输入数值将用于负数冲减！" />

			</view>

			<view class="common-list-ex"  style="background-color: #FFFBE5;">

				<label class="common-list-title-ex"><text class="colorRed">*</text>本期冲销金额(元):</label>

				<input @input="blurclickMen" class="common-list-inpur-ex" type="digit"  v-model="currentMen"
					:disabled="disabledMen" placeholder="所输入数值将用于负数冲减！" />

			</view>
			<!-- <view class="common-list-ex">
			
				<label class="common-list-title-ex">单价（元） :</label>
			
				<text class="common-list-text-ex">{{item.value7}}</text>
			
		</view> -->

			<view class="common-list-ex">

				<label class="common-list-title-ex">累计验工数量 :</label>

				<text class="common-list-text-ex">{{leijiNum}}</text>

			</view>
			<view class="common-list-ex">

				<label class="common-list-title-ex">累计验工金额 :</label>

				<text class="common-list-text-ex">{{leijiMen}}</text>

			</view>
		</view>

		<view class="common-btn-body">
			<button class="common-btn" type="warn" v-debounce="save">提交</button>
			<button class="common-btn" @click="quxiao()" style="border:1px solid #EB4B4B;color:#EB4B4B ;">取消</button>
		</view>

	</view>
</template>

<script>
	import talkingdata from '../../common/talkingdata.js';
	var mThis
	export default {
		data() {
			return {
				checked: true,
				checked2: false,
				radioList: [{
						name: '进度款',
						value: "jindu"
					},
					{
						name: '收付款（含安全生产费）',
						disabled: "shoufu"
					}
				],

				baseList: [],
				addlist: [],
				alerts: '',
				accordion: false,

				prjId: '',
				indexItem: '',
				currentjindu: '0',
				currentNum: '',
				currentMen: '',
				disabledNum: false,
				disabledMen: false,
				leijiNum: '0',
				leijiMen: '0',
				sfkflag: false,
				itemStyle:{
					border:'1px solid #EAEAEA',
				},
				titleFlag:true
			}
		},
		onLoad(option) {
			if(uni.getStorageSync('moaType')=="0"){
					this.titleFlag=false
			}
			this.prjId = option.prjId
			this.indexItem = option.index
			console.log("this.prjId==" + this.prjId)
			console.log("this.indexItem==" + this.indexItem)
			this.getList()

		},
		onReady(){
			console.log("执行onReady")
			
			//在页面挂载完成后，调用外部埋点，统计数据
			 const script= document.createElement('script');
			 script.type = 'text/javascript';
			 script.src = talkingdata.talkingKey;
			 document.body.appendChild(script);
			
		},
		// onBackPress(options) {
		// 	if (options.from === 'navigateBack') {
		// 		console.log("触发1")
		// 		return false;
		// 	}
		// 	console.log("触发2")
		// 	this.back();
		// 	return true;
		// },
		methods: {
			back() {
				uni.navigateBack({
					delta: 1
				});
			},	
	
			quxiao() {
				//this.currentjindu="";
				this.currentNum = "";
				this.currentMen = "";
				this.leijiNum = '0';
				this.leijiMen = '0';
				// uni.navigateBack({

				// })
			},
			inputClick() {
				let price = JSON.parse(JSON.stringify(this.currentjindu));

				price = price
					.replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
					.replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
					.replace(".", "$#$")
					.replace(/\./g, "")
					.replace("$#$", ".")
					.replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3"); // 只能输入两个小数
				if (price.length > 8) {
					//限制最多输入八位字符
					price = price.slice(0, 8);
				}
				if (price.indexOf(".") < 0 && price != "") {
					// 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
					price = parseFloat(price);
				}
				//this.currentjindu = price;
				console.log("1触发校验" + price)
				setTimeout(() => {
					this.currentjindu = price;
				}, 100)



			},
			blurclick() {
				//控制保留4位start
				let val = JSON.parse(JSON.stringify(this.currentNum));

				val = val
					.replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
					.replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
					.replace(".", "$#$")
					.replace(/\./g, "")
					.replace("$#$", ".")
					.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, '$1$2.$3'); // 只能输入四个小数
				if (val.length > 8) {
					//限制最多输入八位字符
					val = val.slice(0, 8);
				}
				if (val.indexOf(".") < 0 && val != "") {
					// 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
					val = parseFloat(val);
				}
				//this.currentjindu = val;
				console.log("1触发校验" + val)
				setTimeout(() => {
					this.currentNum = val;
				}, 100)
				//end
				console.log("1==" + this.currentNum)
				console.log("2==" + this.leijiNum)
				//冲销的金额和数量不大于付款类型为进度款的累积的金额和数量
				if (this.currentNum != undefined && this.currentNum != "") {
					let that = this
					if(Number(this.currentNum)>Number(this.baseList[0].sumNum)){
						uni.showModal({
							confirmColor: '#eb4b4b',
							title: '温馨提示',
							content: "进度款的冲销的金额和数量不大于累积的金额和数量",
							showCancel: false,
							success: function() {
									that.currentNum = "";
									that.currentMen = "";
									that.leijiNum = '0';
									that.leijiMen = '0';
							}
						})
						return;
					}
				}
				this.blurClickOne();


			},
			blurClickOne(){
				if (this.baseList[0].onlyBe1Flag == "N") {
					if (this.currentNum != undefined && this.currentNum != "") {
						this.currentMen = this.baseList[0].price * this.currentNum
						this.currentMen = this.currentMen.toFixed(4); // 只能输入四个小数
						this.leijiNum = Number(this.baseList[0].sumNum) - Number(this.currentNum)
						this.leijiNum = this.leijiNum.toFixed(4); // 只能输入四个小数

						this.blurClickTwo();
						this.blurClickThree();

					}

				}
			},
			blurClickTwo(){
				if (this.currentMen) {
					console.log("触发");
					this.leijiMen = Number(this.baseList[0].sumMoney) - Number(this.currentMen)
					this.leijiMen = this.leijiMen.toFixed(4) //只能输入四个小数
				}else{
					console.log(111)
				}
			},
			blurClickThree(){
				if (this.baseList[0].sumNum !== this.baseList[0].shNum && this.baseList[0].sumNum !== 0) {
					this.menflag = this.currentMen
					console.log("等于1触发" + this.menflag);
					console.log("可以修改");
				} else {
					console.log("不能修改");
					this.disabledMen = true
				}
			},
			blurclickMen() {
				console.log("触发")
				//控制保留4位start
				let val = JSON.parse(JSON.stringify(this.currentMen));

				val = val
					.replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
					.replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
					.replace(".", "$#$")
					.replace(/\./g, "")
					.replace("$#$", ".")
					.replace(/^(\-)*(\d+)\.(\d\d\d\d).*$/, '$1$2.$3'); // 只能输入四个小数
				if (val.length > 8) {
					//限制最多输入八位字符
					val = val.slice(0, 8);
				}
				if (val.indexOf(".") < 0 && val != "") {
					// 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
					val = parseFloat(val);
				}
				//this.currentjindu = val;
				console.log("1触发校验" + val)
				setTimeout(() => {
					this.currentMen = val;
				}, 100)
				//end
				if (this.baseList[0].onlyBe1Flag == "N") {

					if (this.currentNum == "1" && this.currentMen != "") {
						this.blurclickMenOne();
					}
				}
				this.leijiMen = Number(this.baseList[0].sumMoney) - Number(this.currentMen)
				this.leijiMen = this.leijiMen.toFixed(4)
			},
			blurclickMenOne(){
				let that=this;
				if (Number(this.currentMen) > (Number(this.menflag) + 10) || Number(this.currentMen) < (Number(this.menflag) + 10)) {
					console.log("出错");
					uni.showModal({confirmColor: '#eb4b4b',
						title: '温馨提示',
						content: '验工计价金额只能在系统计算的合价范围内上下浮动10元',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								that.currentNum = that.menflag.toFixed(4)
							}
						}
					})
				}
			},
			/**
			 * @author: MrLiu
			 * @time: 2021-09-15
			 * @Title: 工序详情
			 */
			getList() {
				let that = this
				uni.showLoading({
					title: '加载中...',
					mask: true
				});

				console.log('传入参数' + this.prjId);

				uni.request({
					url: uni.getStorageSync('url') + "/pms/app/service/queryValuationDetails?prjId=" + that.prjId,
					method: 'POST',
					dataType: 'json',
					timeout: 10000 * 60,
					header: {
						'pmsToken': uni.getStorageSync('pmsToken')
					},
					data: {

					},
					success: (res) => {
						uni.hideLoading();
						//console.log('列表数据:' + JSON.stringify(res));

						var data = res.data;
						var result = JSON.stringify(data)
						//console.log('列表数据:' + result);
						if (data.resultStat == "000") {

							that.baseList.push(data.valuationInfo[that.indexItem])
							console.log('列表数据:' + JSON.stringify(that.baseList));
							//只有有收付款的 才能冲销收付款。 首付款只能是1条。 冲销收付款直接 带出
							// console.log('列表数据:' + JSON.stringify(that.baseList[0].valuationDetails));
							for (var i = 0; i < that.baseList[0].valuationDetails.length; i++) {
								if ('FIRST' == that.baseList[0].valuationDetails[i].payType) {
									console.log('进入');
									that.sfkflag = true
									
									return;
								}

							}

							that.getListOne();

						} else {
							uni.showModal({confirmColor: '#eb4b4b',
								title: '温馨提示',
								content: data.message,
								showCancel: false,
							})
						}

						uni.hideLoading();
						uni.stopPullDownRefresh();

					},
					fail: (data, code) => {
						uni.hideLoading();
						uni.stopPullDownRefresh();
						console.log('fail' + JSON.stringify(data));
					}
				});
			},
			getListOne(){
				let that=this;
				if (that.baseList[0].onlyBe1Flag != "" || that.baseList[0].onlyBe1Flag != null) {
					//如果这个字段是Y   那么数量只能填写1   本次验工计价金额需要人工填写
					if (that.baseList[0].onlyBe1Flag == "Y") {
						that.currentNum = "1"
						that.disabledNum = true
						//onlyBe1Flag=Y时，若累计验工金额等于预估单金额，则进度必须100%
						if (that.baseList[0].sumMoney === that.baseList[0].shMoney) {
							that.currentjindu = "100%"
						}
					}
				}
			},
			/**
			 * @author: MrLiu
			 * @time: 2021-11-23
			 * @Title: 保存
			 */
			getCheckOne(){
				return new Promise((resolve,reject) => {
					if(this.currentjindu == ""){
						uni.showModal({
							confirmColor: '#eb4b4b',
							title: '温馨提示',
							content: "请输入项目进度",
							showCancel: false,
						})
						reject('fail')
					}else{
						resolve('success')
					}
				});
			},
			getCheckTwo(){
				return new Promise((resolve,reject) => {
					if(this.currentNum == ""){
						uni.showModal({
							confirmColor: '#eb4b4b',
							title: '温馨提示',
							content: "请输入本期验工数量",
							showCancel: false,
						})
						reject('fail')
					}else{
						resolve('success')
					}
				});
			},
			getCheckThree(){
				return new Promise((resolve,reject) => {
					if(this.currentMen == ""){
						uni.showModal({
							confirmColor: '#eb4b4b',
							title: '温馨提示',
							content: "请输入本期验工金额",
							showCancel: false,
						})
						reject('fail')
					}else{
						resolve('success')
					}
				});
			},
			async save() {
				let that = this
				await this.getCheckOne();
				await this.getCheckTwo();
				await this.getCheckThree();
				// if (that.currentjindu == "") {
				// 	uni.showModal({confirmColor: '#eb4b4b',
				// 		title: '温馨提示',
				// 		content: "请输入项目进度",
				// 		showCancel: false,
				// 	})
				// 	return;
				// }
				// if (that.currentNum == "") {
				// 	uni.showModal({confirmColor: '#eb4b4b',
				// 		title: '温馨提示',
				// 		content: "请输入本期验工数量",
				// 		showCancel: false,
				// 	})
				// 	return;
				// }
				// if (that.currentMen == "") {
				// 	uni.showModal({confirmColor: '#eb4b4b',
				// 		title: '温馨提示',
				// 		content: "请输入本期验工金额",
				// 		showCancel: false,
				// 	})
				// 	return;
				// }
				//当前验工计价进度为100%时修改提示
				let tit = ""
				if(that.currentjindu == "100"){
					tit= "当前验工计价将全量冲销"
				}else{
					tit= "提示"
				}

				//	console.log('传入参数' + this.prjId);
				console.log('传入参数' + that.baseList[0].valuationId);
				let id = that.baseList[0].valuationId
				uni.showModal({
					confirmColor: '#eb4b4b',
					title: tit,
					content: "是否确认提交？",

					success: function(res1) {
						if (res1.confirm) {
							uni.showLoading({
								title: '加载中...',
								mask: true
							});
							console.log(that.checked + '类型' + that.checked2);
							let check = ''
							if (that.checked) {
								check = "PROGRESSING"

								console.log('check1=' + check);
								//return;
							} else {
								check = "FIRST"
								console.log('check2=' + check);
								//return;
							}
							let params = [{
								valuationId: id,
								payType: check,
								currentInspectionNum: that.currentNum,
								currentInspectionMoney: that.currentMen,
								projectProgress: that.currentjindu,
								action: "cancel",
							}];
							console.log("参数" + JSON.stringify(params))
						    that.addValuationDetail(params);

						}
					}
				});

			},
			addValuationDetail(params){
				uni.request({
					url: uni.getStorageSync('url') + "/pms/app/service/addValuationDetail",
					method: 'POST',
					dataType: 'json',
					timeout: 10000 * 60,
					header: {
						'pmsToken': uni.getStorageSync('pmsToken')
					},
					data: params,
					success: (res) => {
						uni.hideLoading();
						//console.log('列表数据:' + JSON.stringify(res));

						var data = res.data;
						var result = JSON.stringify(data)
						console.log('列表数据:' + result);
						if (data.resultStat == "000") {
							uni.showModal({confirmColor: '#eb4b4b',
								title: '温馨提示',
								content: data.message,
								showCancel: false,
								success: function() {
									//该方法用于刷新父页面
									uni.navigateBack({
										delta: 1
									})
								}
							})
						} else {
							uni.showModal({confirmColor: '#eb4b4b',
								title: '温馨提示',
								content: data.message,
								showCancel: false,
							})
						}

						uni.hideLoading();
						uni.stopPullDownRefresh();

					},
					fail: (data, code) => {
						uni.hideLoading();
						uni.stopPullDownRefresh();
						console.log('fail' + JSON.stringify(data));
					}
				});
			},
			radioChange() {

				if (this.checked == false) {
					this.checked = true
					this.checked2 = false
					this.currentNum = "";
					this.currentMen = "";
					this.leijiNum = '0';
					this.leijiMen = '0';
					console.log(this.checked + "触发1" + this.checked2)
				}

			},
			radioChange2() {

				this.checked = false
				this.checked2 = true
				console.log(this.checked + "触发2" + this.checked2)
				
				for (var i = 0; i < this.baseList[0].valuationDetails.length; i++) {
					if ('FIRST' == this.baseList[0].valuationDetails[i].payType) {
						this.currentNum = this.baseList[0].valuationDetails[i].currentInspectionNum
						this.currentMen = this.baseList[0].valuationDetails[i].currentInspectionMoney
						this.disabledNum = true
						this.disabledMen = true
						this.leijiNum = Number(this.baseList[0].sumNum) - Number(this.currentNum)
						this.leijiMen = Number(this.baseList[0].sumMoney) - Number(this.currentMen)
						return;
					}
				
				}
				
			},
			chuliNum(params) {

				let newpar = parseFloat(params);

				let reg = /^[0-9]+.?[0-9]*$/;

				if (reg.test(newpar)) {

					let newNum = newpar.toFixed(3);

					return newNum;

				} else {

					alert('请输入数字');

					return;

				}

			}


		}
	}
</script>


<style>
	@import '@/common/common-ui.css';
</style>
